package rpc_netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc_netty.RegistryImpl.ServiceRegistryProvider;
import rpc_netty.server.ServiceProvider.DefaultServiceProvider;
import rpc_1.Service.RpcException;
import rpc_netty.Annotation.ServiceScan;
import rpc_netty.Encoder.CommonDecoder;
import rpc_netty.Encoder.CommonEncoder;
import rpc_netty.Handler.NettyServerHandler;
import rpc_netty.NacosUtils.ShutDownHook;
import rpc_netty.Serializer.KryoSerializer;
import rpc_netty.server.conf.ConfigureMagment;

import javax.rmi.PortableRemoteObject;


@ServiceScan
public class NettyServer_annotation extends AbstractRpcServer {
    private static final Logger logger= LoggerFactory.getLogger(NettyServer_nacos.class);
    private static final ConfigureMagment configureMagment=ConfigureMagment.getConfigureMagment();

    /*
    这里的两个参数无实际意义，真正的host和port会从configureMagment中读取
    这两个参数是为了兼容之前的版本的
     */
    public NettyServer_annotation(String host, int port) throws RpcException {
        /*
        从配置类configureMagment中读取配置并加载
         */
        //读取注册中心种类
        String serviceRegistryType = configureMagment.getProperty("ServiceRegistryType");
        serviceRegistry= ServiceRegistryProvider.getByName(serviceRegistryType);
        //读取注册中心url
        String addr = configureMagment.getProperty("ServiceRegistryUrl");
        serviceRegistry.SetAdd_And_Create(addr);
        serviceProvider=new DefaultServiceProvider();
        String currentServiceUrl = configureMagment.getProperty("CurrentServiceUrl");
        //读取该服务将要运行的url（同样也是暴露给注册中心的url）
        String[] url= currentServiceUrl.split(":");
        this.host=url[0];
        this.port=Integer.parseInt(url[1]);
        //调用父类的方法，扫描service所在的包并且把相应service类自动注册
        scanServices();
    }

    @Override
    public void start(int p) {
        //在服务端下线的时候，自动进行服务注销
        ShutDownHook.getShutDownHook().addClearAllHook();
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker=new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss,worker)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler())
                    .option(ChannelOption.SO_BACKLOG,256)//指定tcp全连接队列大小
                    .option(ChannelOption.SO_KEEPALIVE,true)//心跳机制
                    .childOption(ChannelOption.TCP_NODELAY,true)//关闭nagle算法，保证有数据就及时发送
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //pipeline.addLast(new CommonEncoder(new JsonSerializer()));
                            pipeline.addLast(new CommonEncoder(0));
                            pipeline.addLast(new CommonDecoder());
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });
            ChannelFuture future=serverBootstrap.bind(port).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.error("error when starting the server");
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
